package com.flipdf2.serialize.ppml.element;

import java.util.ArrayList;
import java.util.List;

import org.jdom.Element;
import org.jdom.Namespace;

import com.flipdf2.serialize.ppml.PPMLException;

public class PPMLObject {
	public static final String NAME = "OBJECT";
	
	private List<PPMLMetadata> metadataList;
	private PPMLSource source;
	private PPMLView view;
	
	private String datasetClass;
	private double[] position;
	
	public Element toXML(Namespace defaultNamespace) {
		Element root = null;
		if (defaultNamespace != null) {
			root = new Element(NAME, defaultNamespace);
		} else {
			root = new Element(NAME);	
		}
		
		if (metadataList != null && metadataList.size() > 0) {
			for (int i = 0, n = metadataList.size(); i < n; i++) {
				root.addContent(metadataList.get(i).toXML(defaultNamespace));
			}
		}
		
		if (source != null)
			root.addContent(source.toXML(defaultNamespace));
		
		if (view != null)
			root.addContent(view.toXML(defaultNamespace));

		if (datasetClass != null) 
			root.setAttribute("Class", datasetClass);
		if (position != null) 
			root.setAttribute("Position", position[0] + " " + position[1]);
		
		return root;
	}

	public void check() throws PPMLException {
		if (position == null) {
			throw PPMLException.getInstance(PPMLException.REQUIRED_ATTRIBUTE_LOST, "Position");
		}
		if (source == null) {
			throw PPMLException.getInstance(PPMLException.REQUIRED_ELEMENT_LOST, "Source");
		}
	}

	public String getDatasetClass() {
		return datasetClass;
	}

	public void setDatasetClass(String datasetClass) {
		this.datasetClass = datasetClass;
	}

	public List<PPMLMetadata> getMetadataList() {
		return metadataList;
	}

	public void setMetadataList(List<PPMLMetadata> metadataList) {
		this.metadataList = metadataList;
	}
	
	public void addMetadata(PPMLMetadata metadata) {
		if (this.metadataList == null)
			this.metadataList = new ArrayList<PPMLMetadata>();
		this.metadataList.add(metadata);
	}

	public double[] getPosition() {
		return position;
	}

	public void setPosition(double[] position) {
		this.position = position;
	}

	public PPMLSource getSource() {
		return source;
	}

	public void setSource(PPMLSource source) {
		this.source = source;
	}

	public PPMLView getView() {
		return view;
	}

	public void setView(PPMLView view) {
		this.view = view;
	}
}
